package com.tm.util;

/**
 * 微信web开发 JSAPI初始配置工具类
 */
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import com.tm.pay.config.WechatConfig2; 

public class WeixinConfigUtil {

	    /**
	     * 方法名：getWxConfig</br> 
	     * 详述：获取微信的配置信息 </br> 
	     * @param request
	     * @return
	     * @throws Exception
	     */
	    public static Map<String, Object> getWxConfig(HttpServletRequest request) throws Exception {  
	        Map<String, Object> ret = new HashMap<String, Object>();  
	        
	        String appId = WechatConfig2.GZ_APPID; // 必填，公众号的唯一标识  
	        String secret = WechatConfig2.GZ_SECRET;  
	  
	        String requestUrl = request.getRequestURL().toString();  //"http://114.218.172.191:5555/index";
	        String access_token = "";  
	        String jsapi_ticket = "";  
	        String timestamp = Long.toString(System.currentTimeMillis() / 1000); // 必填，生成签名的时间戳  
	        String nonceStr = UUID.randomUUID().toString(); // 必填，生成签名的随机串  
	        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ appId + "&secret=" + secret;  
	        
	        Map<String, String> sParaTemp = new HashMap<String, String>();
	        
	        String jsonStr = HttpRemoteCall.buildRequest(url, sParaTemp, "utf-8", "", "", "GET");
	        
	        Map<String, String> json = JSONUtilsEx.deserialize(jsonStr, Map.class);
	        
	        if (json != null) {  
	            //要注意，access_token需要缓存  
	        	access_token = json.get("access_token"); 
	              
	            url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+ access_token + "&type=jsapi"; 
	            
	            jsonStr = HttpRemoteCall.buildRequest(url, sParaTemp, "utf-8", "", "", "GET");
	            
	            json = JSONUtilsEx.deserialize(jsonStr, Map.class);
	            
	            if (json != null) {  
	            	jsapi_ticket = json.get("ticket");  
	            }  
	        }  
	        String signature = "";  
	        // 注意这里参数名必须全部小写，且必须有序  
	        String sign = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonceStr+ "&timestamp=" + timestamp + "&url=" + requestUrl;  
	        try {  
	            MessageDigest crypt = MessageDigest.getInstance("SHA-1");  
	            crypt.reset();  
	            crypt.update(sign.getBytes("UTF-8"));  
	            signature = byteToHex(crypt.digest());  
	        } catch (NoSuchAlgorithmException e) {  
	            e.printStackTrace();  
	        } catch (UnsupportedEncodingException e) {  
	            e.printStackTrace();  
	        }  
	        ret.put("appId", appId);  
	        ret.put("timestamp", timestamp);  
	        ret.put("nonceStr", nonceStr);  
	        ret.put("signature", signature);  
	        return ret;  
	    }  
	  
	      
	    /** 
	     * 方法名：byteToHex</br> 
	     * 详述：字符串加密辅助方法 </br>  
	     * @param hash
	     * @return
	     */
	    private static String byteToHex(final byte[] hash) {  
	        Formatter formatter = new Formatter();  
	        for (byte b : hash) {  
	            formatter.format("%02x", b);  
	        }  
	        String result = formatter.toString();  
	        formatter.close();  
	        return result;  
	  
	    }  
	
}
